import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'

// vuex
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
var loadingInstance = ''
const javaService = axios.create({
  baseURL: '',
  timeout: 6000 // request timeout
})
/* 默认值 */
// 'application/x-www-form-urlencoded'
// 'Content-Type:application/json'
axios.defaults.headers.post['Content-Type'] = 'application/json'
// request interceptor
javaService.interceptors.request.use(
  config => {
    // console.log('config', config)
    if (store.getters.token) {
      config.headers['accessToken'] = getToken() // 正确操作
    }
    // 是否要去加载
    if (config.isLoading) {
      loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }

    return config
  },
  error => {
    // 取消加载
    if (loadingInstance !== '') {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

// response interceptor
javaService.interceptors.response.use(
  response => {
    const res = response.data
    // 取消加载
    if (loadingInstance !== '') {
      loadingInstance.close()
    }
    const { code } = res
    if (code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (code === 401) {
        MessageBox.confirm(res.message, '去登录', {
          confirmButtonText: '登录',
          cancelButtonText: '关闭',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }).catch(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }

      return Promise.reject(res.msg || 'Error')
    } else {
      return res
    }
  },
  error => {
    // 取消加载
    // 加定时器 防止网速过快 出现闪屏现象
    if (loadingInstance !== '') {
      setTimeout(() => {
        loadingInstance.close()
      }, 300)
    }

    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default javaService
